package factory.jdbc;

import factory.DatabaseInfo;

import java.sql.*;

@SuppressWarnings("all")
public class JdbcFactory {

    public static Connection getConnection (DatabaseInfo databaseInfo) {
        Connection con = null;
             try {
                 Class.forName(databaseInfo.getDriver());
                 //连接MySQL数据库时，要写上连接的用户名和密码
                 return DriverManager.getConnection(databaseInfo.getUrl(),
                         databaseInfo.getUserName(), databaseInfo.getPassword());
             }
             catch (Exception e) {
                 e.printStackTrace();
             }
             System.out.println(con);

             return null;
    }

    public static void closeCon (Connection con) {
        try {
            //关闭数据库
            con.close();
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        DatabaseInfo databaseInfo = DatabaseInfo.builder().password("123456")
                .userName("root")
                .url("jdbc:mysql://localhost:3307/test1?characterEncoding=utf-8")
                .driver("com.mysql.cj.jdbc.Driver").build();
        Connection connection = JdbcFactory.getConnection(databaseInfo);
        try {
            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery("select * from user ");
            while (resultSet.next()) {
                System.out.println(resultSet.getString("id"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
